package vip.bblog.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import vip.bblog.common.utils.BaseResult;
import vip.bblog.common.utils.UUIDUtils;
import vip.bblog.user.dao.SystemUserMapper;
import vip.bblog.user.entity.SystemUser;
import vip.bblog.user.service.SystemUserService;

import java.time.LocalDateTime;

/**
 * <p>
 * 系统（后台）用户表 服务实现类
 * </p>
 *
 * @author yuyong
 * @since 2019-04-28
 */
@Service
public class SystemUserServiceImpl extends ServiceImpl<SystemUserMapper, SystemUser> implements SystemUserService {

    @Autowired
    private SystemUserMapper systemUserMapper;

    /**
     * 增加用户
     *
     * @param systemUser
     * @return
     */
    @Override
    public BaseResult<Object> insert(SystemUser systemUser) {
        systemUser.setId(UUIDUtils.getUUID());
        systemUser.setNickname(systemUser.getUsername());
        systemUser.setCreateTime(LocalDateTime.now());
        systemUser.setUpdateTime(LocalDateTime.now());
        systemUserMapper.insert(systemUser);
        return BaseResult.successWithData(systemUser);
    }

    /**
     * 根据id删除用户
     *
     * @param id
     * @return
     */
    @Override
    public BaseResult<Object> deleteById(String id) {
        systemUserMapper.deleteById(id);
        return BaseResult.success();
    }

    /**
     * 模糊分页查询用户
     *
     * @param page
     * @param systemUser
     * @return
     */
    @Override
    public BaseResult<Object> selectPageByExample(Page<SystemUser> page, SystemUser systemUser) {
        QueryWrapper<SystemUser> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(systemUser.getUsername())) {
            queryWrapper.like("username", systemUser.getUsername());
        }
        if (StringUtils.isNotBlank(systemUser.getNickname())) {
            queryWrapper.like("nickname", systemUser.getNickname());
        }
        if (null != systemUser.getSex()) {
            queryWrapper.eq("sex", systemUser.getSex());
        }
        if (null == systemUser.getStatus()) {
            queryWrapper.eq("status", 1);
        } else {
            queryWrapper.eq("status", systemUser.getStatus());
        }
        IPage<SystemUser> pageResult = systemUserMapper.selectPage(page, queryWrapper);
        return BaseResult.successWithData(pageResult);
    }
}
